from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required
from ..utils import success_response, error_response
from .. import db
from ..models import SystemSetting
from . import api

@api.route('/settings', methods=['GET'])
@jwt_required()
def get_settings():
    """获取系统设置"""
    try:
        # 获取所有设置
        settings = SystemSetting.query.all()
        settings_dict = {setting.key: setting.value for setting in settings}
        
        # 添加默认值
        default_settings = {
            'system_name': '路口信控数智融合AI决策系统',
            'version': 'V1.0',
            'theme': '0',
            'auto_save': 'true',
            'email_notify': 'false',
            'sms_notify': 'false'
        }
        
        # 合并默认值和数据库中的设置
        for key, value in default_settings.items():
            if key not in settings_dict:
                settings_dict[key] = value
        
        return success_response(settings_dict, '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取系统设置错误: {str(e)}')
        return error_response('获取系统设置失败', 500)

@api.route('/settings', methods=['POST'])
@jwt_required()
def save_settings():
    """保存系统设置"""
    try:
        data = request.get_json()
        
        # 更新或创建设置项
        for key, value in data.items():
            setting = SystemSetting.query.filter_by(key=key).first()
            if setting:
                setting.value = str(value)
            else:
                setting = SystemSetting(key=key, value=str(value))
                db.session.add(setting)
        
        db.session.commit()
        
        return success_response(None, '设置保存成功')
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'保存系统设置错误: {str(e)}')
        return error_response('设置保存失败', 500)